class_name Unit
extends Node2D

@export var stats: UnitStats

@onready var visuals: Node2D = %Visuals
@onready var sprite: Sprite2D = %Sprite
@onready var animation_player: AnimationPlayer = %AnimationPlayer
@onready var health_component: HealthComponent = %HealthComponent
@onready var health_bar: HealthBar = %HealthBar
@onready var flash_timer: Timer = %FlashTimer


func _ready() -> void:
	sprite.texture = stats.icon
	health_component.setup(stats)

func set_flash_material() -> void:
	sprite.material = Global.FLASH_MATERIAL
	flash_timer.start()

func _on_hurtbox_component_on_damage(hitbox: HitboxComponent) -> void:
	if health_component.is_died():
		return
	var blocked := Global.is_chance_success(stats.block_chance / 100)
	if blocked:
		Global.create_block_text(self)
		return
	health_component.take_damage(hitbox.damage)
	set_flash_material()
	Global.create_damage_text(self, hitbox)


func _on_health_component_on_health_changed(current_health: float, max_health: float) -> void:
	health_bar.update_bar(current_health / max_health, current_health)


func _on_flash_timer_timeout() -> void:
	sprite.material = null
